package cn.com.dingtek.genius.manager.server.web.security;

import cn.com.dingtek.genius.manager.server.repository.db.entity.UserBase;
import cn.com.dingtek.genius.manager.server.repository.db.manager.UserBaseManager;
import cn.com.dingtek.genius.manager.server.support.sam.Enforcer;
import cn.com.dingtek.genius.manager.server.support.sam.SamToken;
import cn.com.dingtek.genius.manager.server.support.sam.annotation.Logical;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SecurityEnforcer implements Enforcer {
    @Autowired
    private UserBaseManager userBaseManager;

    @Override
    public boolean enforce(SamToken token, String[] policies, Logical logical) {
        UserBase userBase = userBaseManager.getById(token.getUserId());
        if (userBase == null) {
            return false;
        }

//        UserAuthGroup userAuthGroup = userAuthGroupManager.getById(userBase.getAuthGroupId());
//        if (userAuthGroup == null) {
//            return false;
//        }
//
//        long[] policyEffect = Enforcer.BytePolicy.convertPolicyEffect(userAuthGroup.getGroupRules());
//        if (policies.length == 1) {
//            return resolve(policyEffect, policies[0]);
//        }
//
//        if (Logical.AND.equals(logical)) {
//            for (String policy : policies) {
//                if (!resolve(policyEffect, policy)) {
//                    return false;
//                }
//            }
//        }
//
//        if (Logical.OR.equals(logical)) {
//            for (String policy : policies) {
//                if (resolve(policyEffect, policy)) {
//                    return true;
//                }
//            }
//        }

        return false;
    }

    private boolean resolve(long[] policyEffect, String policy) {
        String[] position = policy.split(",");
        if (position == null || position.length != 2) {
            return false;
        }

        return Enforcer.BytePolicy.verify(policyEffect, Integer.valueOf(position[0]), Integer.valueOf(position[1]));
    }
}
